<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>例子</title>
</head>

<body>
    用插件取网页内容的例子
    <button onclick="test()">test</button>
    <script>
        function getHtmlFromUrl(url,id='') {
            return new Promise((resolve, reject) => {
                const requestId = Math.random().toString(36).substring(2);

                // 监听响应
                const messageListener = (event) => {
                    if (event.source === window && event.data.type === 'htmlResponse' &&
                        event.data.requestId === requestId) {
                        window.removeEventListener('message', messageListener);

                        if (event.data.error) {
                            reject(new Error(event.data.error));
                        } else {
                            resolve(event.data.html);
                        }
                    }
                };
                window.addEventListener('message', messageListener);
                // 发送请求到内容脚本
                window.postMessage({
                    type: 'htmlRequest',
                    requestId,
                    targetUrl: url,
                    targetCss:id
                }, '*');

                // 设置超时
                setTimeout(() => {
                    window.removeEventListener('message', messageListener);
                    reject(new Error('请求超时'));
                }, 10000);
            });
        }


        function test() {
            // 使用示例
            getHtmlFromUrl('https://baidu.com')
                .then(html => {
                    console.log('获取到HTML:', html);
                })
                .catch(error => {
                    console.error('获取失败:', error);
                });
        }

    </script>
</body>

</html>